package com.example.agent_springai.tool;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.example.agent_springai.entity.po.*;
import com.example.agent_springai.entity.query.ChainlooseQuery;
import com.example.agent_springai.entity.query.ModuleQuery;
import com.example.agent_springai.entity.query.TemperQuery;
import com.example.agent_springai.entity.query.DrawChartQuery;
import com.example.agent_springai.service.*;
import com.example.agent_springai.util.MCPDrawUtil;
import com.example.agent_springai.util.RandomTimeGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;

@RequiredArgsConstructor
@Component
@Slf4j
public class Tools {

    private final ITemperService temperService;

    private final IChainlooseJ3LDF0Service chainlooseJ3LDF0Service;
    
    private final IChainlooseJ3LDF7Service chainlooseJ3LDF7Service;
    
    private final INormalLDF0Service normalLDF0Service;

    private final IHighcurrentJ3LDF0Service highcurrentJ3LDF0Service;

    private MCPDrawUtil mcpDrawUtil = new MCPDrawUtil();

    private final ObjectMapper objectMapper;

    private static final String MCP_URL = "http://localhost:1122/mcp";

    /**
     * 处理数据中的时间戳，解决同一时间多数据问题
     * @param data 原始数据
     * @return 处理后的数据
     */
    private Object processDataWithTimestamps(Object data) {
        try {
            if (data instanceof List) {
                List<Map<String, Object>> dataList = (List<Map<String, Object>>) data;

                // 检查是否包含timestamp字段
                boolean hasTimestamp = dataList.size() > 0 && dataList.get(0).containsKey("timestamp");

                if (hasTimestamp) {
                    // 使用timestamp字段作为time值
                    List<Map<String, Object>> processedDataList = new ArrayList<>();
                    for (Map<String, Object> item : dataList) {
                        Map<String, Object> newItem = new HashMap<>(item);
                        // 将timestamp转换为适合图表显示的格式
                        if (item.containsKey("timestamp") && item.get("timestamp") != null) {
                            Long timestamp = ((Number) item.get("timestamp")).longValue();
                            // 转换为日期时间格式
                            Instant instant = Instant.ofEpochMilli(timestamp);
                            ZoneId zoneId = ZoneId.systemDefault();
                            DateTimeFormatter formatter =
                                    DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
                            String formattedTime = java.time.ZonedDateTime.ofInstant(instant, zoneId).format(formatter);
                            newItem.put("time", formattedTime);
                        }
                        processedDataList.add(newItem);
                    }
                    return processedDataList;
                } else {
                    // 原有逻辑：处理重复时间点
                    Map<String, Integer> timeGroupCount = new LinkedHashMap<>();

                    // 统计每个时间点的数据数量
                    for (Map<String, Object> item : dataList) {
                        String time = (String) item.get("time");
                        timeGroupCount.put(time, timeGroupCount.getOrDefault(time, 0) + 1);
                    }

                    // 如果有重复时间点，则添加微小的时间偏移
                    Map<String, Integer> timeOffset = new HashMap<>();
                    List<Map<String, Object>> processedDataList = new ArrayList<>();

                    for (Map<String, Object> item : dataList) {
                        String time = (String) item.get("time");
                        Map<String, Object> newItem = new HashMap<>(item);

                        if (timeGroupCount.get(time) > 1) {
                            int offset = timeOffset.getOrDefault(time, 0);
                            if (offset > 0) {
                                // 为重复的时间点添加毫秒偏移
                                String newTime = time + "." + String.format("%03d", offset * 100);
                                newItem.put("time", newTime);
                            }
                            timeOffset.put(time, offset + 1);
                        }

                        processedDataList.add(newItem);
                    }

                    return processedDataList;
                }
            }
        } catch (Exception e) {
            log.warn("处理时间戳时出错，使用原始数据: {}", e.getMessage());
        }

        // 出现异常时返回原始数据
        return data;
    }

    /**
     * 画图工具方法：按MCP要求格式传参（完全对齐测试类格式）
     * @param query 画图查询参数
     */
    @Tool(description = "mcp画图，用户要求画图时调用，支持生成折线图、饼图、柱状图等，参数为结构化查询对象" +
            "同时返回图片链接")
    public String handleDraw(@ToolParam(description = "画图查询参数") DrawChartQuery query) {
        try {
            // 参数校验
            if (query.getData() == null || query.getData().isEmpty()) {
                return "参数错误：data必须是非空数组，例如[{\"time\":\"2025-01\",\"value\":48,\"group\":\"发电机5\"}]";
            }
            if (query.getTitle() == null || query.getTitle().trim().isEmpty()) {
                return "参数错误：title必须是非空字符串（图表标题）";
            }
            if (query.getStyle() == null) {
                query.setStyle(new HashMap<>()); // 设置默认样式
            }

            // 设置默认样式值（如果未提供）
            if (!query.getStyle().containsKey("lineWidth")) {
                query.getStyle().put("lineWidth", 3);
            }
            if (!query.getStyle().containsKey("backgroundColor")) {
                query.getStyle().put("backgroundColor", "#ffffff");
            }
            if (!query.getStyle().containsKey("showLabel")) {
                query.getStyle().put("showLabel", false);
            }

            // 构造DrawChartParam对象
            DrawChartParam param = new DrawChartParam();
            param.setType(query.getType());
            param.setData(processDataWithTimestamps(query.getData()));
            param.setTheme(query.getTheme());
            param.setStyle(query.getStyle());
            param.setWidth(query.getWidth());
            param.setHeight(query.getHeight());
            param.setTitle(query.getTitle());

            // 2. 构建MCP请求（完全对齐测试类格式）
            Map<String, Object> requestMap = mcpDrawUtil.buildMCPRequest(param);

            // 3. 转换为JSON并发送请求
            String requestJson = objectMapper.writeValueAsString(requestMap);
            log.info("发送画图请求，JSON: {}", requestJson);

            HttpResponse<String> response = Unirest.post(MCP_URL)
                    .connectTimeout(10000) // 10秒连接超时
                    .socketTimeout(30000)  // 30秒读取超时
                    .header("Content-Type", "application/json")
                    .header("Accept", "application/json, text/event-stream")
                    .header("User-Agent", "FaultAgent/1.0")
                    .body(requestJson)
                    .asString();

            // 4. 解析响应
            return mcpDrawUtil.parseMCPResponse(response);

        } catch (Exception e) {
            log.error("画图工具执行异常", e);
            return "画图工具异常：" + e.getMessage();
        }
    }

    /**
     * 画图工具方法：生成图表的JSON数据用于前端渲染
     * @param query 画图查询参数
     */
    @Tool(description = "用户要求画图时调用，生成图表的JSON数据用于前端渲染，参数为结构化查询对象" +
            "同时返回JSON")
    public Map<String, Object> handleDrawJson(@ToolParam(description = "画图查询参数") DrawChartQuery query) {
        try {
            // 参数校验
            if (query.getData() == null || query.getData().isEmpty()) {
                throw new IllegalArgumentException("参数错误：data必须是非空数组");
            }
            if (query.getTitle() == null || query.getTitle().trim().isEmpty()) {
                throw new IllegalArgumentException("参数错误：title必须是非空字符串");
            }
            if (query.getStyle() == null) {
                query.setStyle(new HashMap<>()); // 设置默认样式
            }

            // 设置默认样式值（如果未提供）
            if (!query.getStyle().containsKey("lineWidth")) {
                query.getStyle().put("lineWidth", 3);
            }
            if (!query.getStyle().containsKey("backgroundColor")) {
                query.getStyle().put("backgroundColor", "#ffffff");
            }
            if (!query.getStyle().containsKey("showLabel")) {
                query.getStyle().put("showLabel", false);
            }

            // 构造DrawChartParam对象
            DrawChartParam param = new DrawChartParam();
            param.setType(query.getType());
            param.setData(processDataWithTimestamps(query.getData()));
            param.setTheme(query.getTheme());
            param.setStyle(query.getStyle());
            param.setWidth(query.getWidth());
            param.setHeight(query.getHeight());
            param.setTitle(query.getTitle());

            // 构建返回的JSON数据
            Map<String, Object> chartData = new HashMap<>();
            chartData.put("type", param.getType());
            chartData.put("data", param.getData());
            chartData.put("theme", param.getTheme());
            chartData.put("style", param.getStyle());
            chartData.put("width", param.getWidth());
            chartData.put("height", param.getHeight());
            chartData.put("title", param.getTitle());

            log.debug("返回画图数据：{}", chartData);
            return chartData;

        } catch (Exception e) {
            log.error("画图工具执行异常", e);
            throw new RuntimeException("画图工具异常：" + e.getMessage(), e);
        }
    }


    @Tool(description = "用户询问机械臂是否故障了。")
    public String handleDiagnose() {
        try {
            LocalDateTime start = RandomTimeGenerator.start;
            LocalDateTime end = RandomTimeGenerator.end;
            ChainlooseQuery query = new ChainlooseQuery();
            query.setStartTime(start);
            query.setEndTime(end);
            query.setMaxResults(512);
            List<ChainlooseJ3LDF0> chainData = chainlooseJ3LDF0Service.queryChainlooseData(query);

            List<List<Double>> sequence = new ArrayList<>();
            for (ChainlooseJ3LDF0 data : chainData) {
                List<Double> axisData = new ArrayList<>();
                axisData.add(data.getAxis0Efb().doubleValue());
                axisData.add(data.getAxis3Efb().doubleValue());
                axisData.add(data.getAxis4Efb().doubleValue());
                sequence.add(axisData);
            }

            Map<String, Object> reqBody = new HashMap<>();
            reqBody.put("sequence", sequence);
            HttpResponse<String> resp = Unirest.post("http://10.108.13.250:8000/predict")
                    .connectTimeout(10000) // 10秒连接超时
                    .socketTimeout(30000)  // 30秒读取超时
                    .header("Content-Type", "application/json")
                    .header("User-Agent", "FaultAgent/1.0")
                    .body(objectMapper.writeValueAsString(reqBody))
                    .asString();

            return resp.getBody();
        } catch (Exception e) {
            log.error("诊断流程失败", e);
            return e.toString();
        }
    }

    @Tool(description = "根据发电机编号、时间范围、温度范围等条件，动态查询发电机温度数据。")
    public List<Temper> queryTemper(@ToolParam(description = "发电机查询的条件") TemperQuery query) {
        log.info("执行发电机查询，参数：{}", query);
        QueryChainWrapper<Temper> queryWrapper = temperService.query();

        if (query.getGeneratorNo() != null && !query.getGeneratorNo().isEmpty()) {
            queryWrapper.eq("generator_no", query.getGeneratorNo());
        }
        if (query.getStartDate() != null) {
            LocalDateTime startDateTime = query.getStartDate().atStartOfDay();
            queryWrapper.ge("record_time", startDateTime);
        }
        if (query.getEndDate() != null) {
            LocalDateTime endDateTime = query.getEndDate().atTime(LocalTime.MAX);
            queryWrapper.le("record_time", endDateTime);
        }
        if (query.getTemperMax() != null) {
            queryWrapper.le("temperature", query.getTemperMax());
        }
        if (query.getTemperMin() != null) {
            queryWrapper.ge("temperature", query.getTemperMin());
        }
        if (query.getSorts() != null && !query.getSorts().isEmpty()) {
            for (TemperQuery.Sort sort : query.getSorts()) {
                queryWrapper.orderBy(true, sort.getAsc(), sort.getField());
            }
        }

        return queryWrapper.list();
    }

    /**
     * 应用查询条件到QueryWrapper
     * @param queryWrapper 查询包装器
     * @param query 查询条件
     */
    private void applyQueryConditions(QueryChainWrapper<?> queryWrapper, ChainlooseQuery query) {
        if (query.getStartTime() != null) {
            queryWrapper.ge("record_time", query.getStartTime());
        }
        if (query.getEndTime() != null) {
            queryWrapper.le("record_time", query.getEndTime());
        }

        // Axis0参数 - 存在性查询
        if (query.getNeedAxis0Vcmd() != null && query.getNeedAxis0Vcmd()) queryWrapper.isNotNull("axis0_vcmd");
        if (query.getNeedAxis0Vfb() != null && query.getNeedAxis0Vfb()) queryWrapper.isNotNull("axis0_vfb");
        if (query.getNeedAxis0Acmd() != null && query.getNeedAxis0Acmd()) queryWrapper.isNotNull("axis0_acmd");
        if (query.getNeedAxis0Afb() != null && query.getNeedAxis0Afb()) queryWrapper.isNotNull("axis0_afb");
        if (query.getNeedAxis0Ecmd() != null && query.getNeedAxis0Ecmd()) queryWrapper.isNotNull("axis0_ecmd");
        if (query.getNeedAxis0Efb() != null && query.getNeedAxis0Efb()) queryWrapper.isNotNull("axis0_efb");
        
        // Axis0参数 - 范围查询
        if (query.getAxis0VcmdMin() != null) queryWrapper.ge("axis0_vcmd", query.getAxis0VcmdMin());
        if (query.getAxis0VcmdMax() != null) queryWrapper.le("axis0_vcmd", query.getAxis0VcmdMax());
        if (query.getAxis0VfbMin() != null) queryWrapper.ge("axis0_vfb", query.getAxis0VfbMin());
        if (query.getAxis0VfbMax() != null) queryWrapper.le("axis0_vfb", query.getAxis0VfbMax());
        if (query.getAxis0AcmdMin() != null) queryWrapper.ge("axis0_acmd", query.getAxis0AcmdMin());
        if (query.getAxis0AcmdMax() != null) queryWrapper.le("axis0_acmd", query.getAxis0AcmdMax());
        if (query.getAxis0AfbMin() != null) queryWrapper.ge("axis0_afb", query.getAxis0AfbMin());
        if (query.getAxis0AfbMax() != null) queryWrapper.le("axis0_afb", query.getAxis0AfbMax());
        if (query.getAxis0EcmdMin() != null) queryWrapper.ge("axis0_ecmd", query.getAxis0EcmdMin());
        if (query.getAxis0EcmdMax() != null) queryWrapper.le("axis0_ecmd", query.getAxis0EcmdMax());
        if (query.getAxis0EfbMin() != null) queryWrapper.ge("axis0_efb", query.getAxis0EfbMin());
        if (query.getAxis0EfbMax() != null) queryWrapper.le("axis0_efb", query.getAxis0EfbMax());

        // Axis1参数 - 存在性查询
        if (query.getNeedAxis1Vcmd() != null && query.getNeedAxis1Vcmd()) queryWrapper.isNotNull("axis1_vcmd");
        if (query.getNeedAxis1Vfb() != null && query.getNeedAxis1Vfb()) queryWrapper.isNotNull("axis1_vfb");
        if (query.getNeedAxis1Acmd() != null && query.getNeedAxis1Acmd()) queryWrapper.isNotNull("axis1_acmd");
        if (query.getNeedAxis1Afb() != null && query.getNeedAxis1Afb()) queryWrapper.isNotNull("axis1_afb");
        if (query.getNeedAxis1Ecmd() != null && query.getNeedAxis1Ecmd()) queryWrapper.isNotNull("axis1_ecmd");
        if (query.getNeedAxis1Efb() != null && query.getNeedAxis1Efb()) queryWrapper.isNotNull("axis1_efb");
        
        // Axis1参数 - 范围查询
        if (query.getAxis1VcmdMin() != null) queryWrapper.ge("axis1_vcmd", query.getAxis1VcmdMin());
        if (query.getAxis1VcmdMax() != null) queryWrapper.le("axis1_vcmd", query.getAxis1VcmdMax());
        if (query.getAxis1VfbMin() != null) queryWrapper.ge("axis1_vfb", query.getAxis1VfbMin());
        if (query.getAxis1VfbMax() != null) queryWrapper.le("axis1_vfb", query.getAxis1VfbMax());
        if (query.getAxis1AcmdMin() != null) queryWrapper.ge("axis1_acmd", query.getAxis1AcmdMin());
        if (query.getAxis1AcmdMax() != null) queryWrapper.le("axis1_acmd", query.getAxis1AcmdMax());
        if (query.getAxis1AfbMin() != null) queryWrapper.ge("axis1_afb", query.getAxis1AfbMin());
        if (query.getAxis1AfbMax() != null) queryWrapper.le("axis1_afb", query.getAxis1AfbMax());
        if (query.getAxis1EcmdMin() != null) queryWrapper.ge("axis1_ecmd", query.getAxis1EcmdMin());
        if (query.getAxis1EcmdMax() != null) queryWrapper.le("axis1_ecmd", query.getAxis1EcmdMax());
        if (query.getAxis1EfbMin() != null) queryWrapper.ge("axis1_efb", query.getAxis1EfbMin());
        if (query.getAxis1EfbMax() != null) queryWrapper.le("axis1_efb", query.getAxis1EfbMax());

        // Axis2参数 - 存在性查询
        if (query.getNeedAxis2Vcmd() != null && query.getNeedAxis2Vcmd()) queryWrapper.isNotNull("axis2_vcmd");
        if (query.getNeedAxis2Vfb() != null && query.getNeedAxis2Vfb()) queryWrapper.isNotNull("axis2_vfb");
        if (query.getNeedAxis2Acmd() != null && query.getNeedAxis2Acmd()) queryWrapper.isNotNull("axis2_acmd");
        if (query.getNeedAxis2Afb() != null && query.getNeedAxis2Afb()) queryWrapper.isNotNull("axis2_afb");
        if (query.getNeedAxis2Ecmd() != null && query.getNeedAxis2Ecmd()) queryWrapper.isNotNull("axis2_ecmd");
        if (query.getNeedAxis2Efb() != null && query.getNeedAxis2Efb()) queryWrapper.isNotNull("axis2_efb");
        
        // Axis2参数 - 范围查询
        if (query.getAxis2VcmdMin() != null) queryWrapper.ge("axis2_vcmd", query.getAxis2VcmdMin());
        if (query.getAxis2VcmdMax() != null) queryWrapper.le("axis2_vcmd", query.getAxis2VcmdMax());
        if (query.getAxis2VfbMin() != null) queryWrapper.ge("axis2_vfb", query.getAxis2VfbMin());
        if (query.getAxis2VfbMax() != null) queryWrapper.le("axis2_vfb", query.getAxis2VfbMax());
        if (query.getAxis2AcmdMin() != null) queryWrapper.ge("axis2_acmd", query.getAxis2AcmdMin());
        if (query.getAxis2AcmdMax() != null) queryWrapper.le("axis2_acmd", query.getAxis2AcmdMax());
        if (query.getAxis2AfbMin() != null) queryWrapper.ge("axis2_afb", query.getAxis2AfbMin());
        if (query.getAxis2AfbMax() != null) queryWrapper.le("axis2_afb", query.getAxis2AfbMax());
        if (query.getAxis2EcmdMin() != null) queryWrapper.ge("axis2_ecmd", query.getAxis2EcmdMin());
        if (query.getAxis2EcmdMax() != null) queryWrapper.le("axis2_ecmd", query.getAxis2EcmdMax());
        if (query.getAxis2EfbMin() != null) queryWrapper.ge("axis2_efb", query.getAxis2EfbMin());
        if (query.getAxis2EfbMax() != null) queryWrapper.le("axis2_efb", query.getAxis2EfbMax());

        // Axis3参数 - 存在性查询
        if (query.getNeedAxis3Vcmd() != null && query.getNeedAxis3Vcmd()) queryWrapper.isNotNull("axis3_vcmd");
        if (query.getNeedAxis3Vfb() != null && query.getNeedAxis3Vfb()) queryWrapper.isNotNull("axis3_vfb");
        if (query.getNeedAxis3Acmd() != null && query.getNeedAxis3Acmd()) queryWrapper.isNotNull("axis3_acmd");
        if (query.getNeedAxis3Afb() != null && query.getNeedAxis3Afb()) queryWrapper.isNotNull("axis3_afb");
        if (query.getNeedAxis3Ecmd() != null && query.getNeedAxis3Ecmd()) queryWrapper.isNotNull("axis3_ecmd");
        if (query.getNeedAxis3Efb() != null && query.getNeedAxis3Efb()) queryWrapper.isNotNull("axis3_efb");
        
        // Axis3参数 - 范围查询
        if (query.getAxis3VcmdMin() != null) queryWrapper.ge("axis3_vcmd", query.getAxis3VcmdMin());
        if (query.getAxis3VcmdMax() != null) queryWrapper.le("axis3_vcmd", query.getAxis3VcmdMax());
        if (query.getAxis3VfbMin() != null) queryWrapper.ge("axis3_vfb", query.getAxis3VfbMin());
        if (query.getAxis3VfbMax() != null) queryWrapper.le("axis3_vfb", query.getAxis3VfbMax());
        if (query.getAxis3AcmdMin() != null) queryWrapper.ge("axis3_acmd", query.getAxis3AcmdMin());
        if (query.getAxis3AcmdMax() != null) queryWrapper.le("axis3_acmd", query.getAxis3AcmdMax());
        if (query.getAxis3AfbMin() != null) queryWrapper.ge("axis3_afb", query.getAxis3AfbMin());
        if (query.getAxis3AfbMax() != null) queryWrapper.le("axis3_afb", query.getAxis3AfbMax());
        if (query.getAxis3EcmdMin() != null) queryWrapper.ge("axis3_ecmd", query.getAxis3EcmdMin());
        if (query.getAxis3EcmdMax() != null) queryWrapper.le("axis3_ecmd", query.getAxis3EcmdMax());
        if (query.getAxis3EfbMin() != null) queryWrapper.ge("axis3_efb", query.getAxis3EfbMin());
        if (query.getAxis3EfbMax() != null) queryWrapper.le("axis3_efb", query.getAxis3EfbMax());

        // Axis4参数 - 存在性查询
        if (query.getNeedAxis4Vcmd() != null && query.getNeedAxis4Vcmd()) queryWrapper.isNotNull("axis4_vcmd");
        if (query.getNeedAxis4Vfb() != null && query.getNeedAxis4Vfb()) queryWrapper.isNotNull("axis4_vfb");
        if (query.getNeedAxis4Acmd() != null && query.getNeedAxis4Acmd()) queryWrapper.isNotNull("axis4_acmd");
        if (query.getNeedAxis4Afb() != null && query.getNeedAxis4Afb()) queryWrapper.isNotNull("axis4_afb");
        if (query.getNeedAxis4Ecmd() != null && query.getNeedAxis4Ecmd()) queryWrapper.isNotNull("axis4_ecmd");
        if (query.getNeedAxis4Efb() != null && query.getNeedAxis4Efb()) queryWrapper.isNotNull("axis4_efb");
        
        // Axis4参数 - 范围查询
        if (query.getAxis4VcmdMin() != null) queryWrapper.ge("axis4_vcmd", query.getAxis4VcmdMin());
        if (query.getAxis4VcmdMax() != null) queryWrapper.le("axis4_vcmd", query.getAxis4VcmdMax());
        if (query.getAxis4VfbMin() != null) queryWrapper.ge("axis4_vfb", query.getAxis4VfbMin());
        if (query.getAxis4VfbMax() != null) queryWrapper.le("axis4_vfb", query.getAxis4VfbMax());
        if (query.getAxis4AcmdMin() != null) queryWrapper.ge("axis4_acmd", query.getAxis4AcmdMin());
        if (query.getAxis4AcmdMax() != null) queryWrapper.le("axis4_acmd", query.getAxis4AcmdMax());
        if (query.getAxis4AfbMin() != null) queryWrapper.ge("axis4_afb", query.getAxis4AfbMin());
        if (query.getAxis4AfbMax() != null) queryWrapper.le("axis4_afb", query.getAxis4AfbMax());
        if (query.getAxis4EcmdMin() != null) queryWrapper.ge("axis4_ecmd", query.getAxis4EcmdMin());
        if (query.getAxis4EcmdMax() != null) queryWrapper.le("axis4_ecmd", query.getAxis4EcmdMax());
        if (query.getAxis4EfbMin() != null) queryWrapper.ge("axis4_efb", query.getAxis4EfbMin());
        if (query.getAxis4EfbMax() != null) queryWrapper.le("axis4_efb", query.getAxis4EfbMax());

        // Axis5参数 - 存在性查询
        if (query.getNeedAxis5Vcmd() != null && query.getNeedAxis5Vcmd()) queryWrapper.isNotNull("axis5_vcmd");
        if (query.getNeedAxis5Vfb() != null && query.getNeedAxis5Vfb()) queryWrapper.isNotNull("axis5_vfb");
        if (query.getNeedAxis5Acmd() != null && query.getNeedAxis5Acmd()) queryWrapper.isNotNull("axis5_acmd");
        if (query.getNeedAxis5Afb() != null && query.getNeedAxis5Afb()) queryWrapper.isNotNull("axis5_afb");
        if (query.getNeedAxis5Ecmd() != null && query.getNeedAxis5Ecmd()) queryWrapper.isNotNull("axis5_ecmd");
        if (query.getNeedAxis5Efb() != null && query.getNeedAxis5Efb()) queryWrapper.isNotNull("axis5_efb");
        
        // Axis5参数 - 范围查询
        if (query.getAxis5VcmdMin() != null) queryWrapper.ge("axis5_vcmd", query.getAxis5VcmdMin());
        if (query.getAxis5VcmdMax() != null) queryWrapper.le("axis5_vcmd", query.getAxis5VcmdMax());
        if (query.getAxis5VfbMin() != null) queryWrapper.ge("axis5_vfb", query.getAxis5VfbMin());
        if (query.getAxis5VfbMax() != null) queryWrapper.le("axis5_vfb", query.getAxis5VfbMax());
        if (query.getAxis5AcmdMin() != null) queryWrapper.ge("axis5_acmd", query.getAxis5AcmdMin());
        if (query.getAxis5AcmdMax() != null) queryWrapper.le("axis5_acmd", query.getAxis5AcmdMax());
        if (query.getAxis5AfbMin() != null) queryWrapper.ge("axis5_afb", query.getAxis5AfbMin());
        if (query.getAxis5AfbMax() != null) queryWrapper.le("axis5_afb", query.getAxis5AfbMax());
        if (query.getAxis5EcmdMin() != null) queryWrapper.ge("axis5_ecmd", query.getAxis5EcmdMin());
        if (query.getAxis5EcmdMax() != null) queryWrapper.le("axis5_ecmd", query.getAxis5EcmdMax());
        if (query.getAxis5EfbMin() != null) queryWrapper.ge("axis5_efb", query.getAxis5EfbMin());
        if (query.getAxis5EfbMax() != null) queryWrapper.le("axis5_efb", query.getAxis5EfbMax());

        // 限制返回记录数
        if (query.getMaxResults() != null && query.getMaxResults() > 0) {
            queryWrapper.last("LIMIT " + query.getMaxResults());
        }

        // 排序
        if (query.getSorts() != null && !query.getSorts().isEmpty()) {
            for (ChainlooseQuery.Sort sort : query.getSorts()) {
                queryWrapper.orderBy(true, sort.getAsc(), sort.getField());
            }
        }
    }

    /**
     * 机械臂J3传动链松动、负载为0、运动轨迹LDF数据。根据时间范围查询机械臂数据，
     * 或者查询轴的参数（Vcmd: 指令速度、Vfb: 反馈速度、Acmd: 指令加速度、Afb: 反馈加速度、Ecmd: 指令误差、Efb: 反馈电流）。
     */
    @Tool(description = "机械臂J3传动链松动、负载为0、运动轨迹LDF数据。根据时间范围查询机械臂数据，" +
            "或者查询轴的参数（Vcmd: 指令速度、Vfb: 反馈速度、Acmd: 指令加速度、Afb: 反馈加速度、Ecmd: 指令误差、Efb: 反馈电流）。")
    public List<ChainlooseJ3LDF0> queryChainlooseData(@ToolParam(description = "机械臂查询的条件") ChainlooseQuery query) {
        log.info("执行机械臂数据查询，参数：{}", query);
        QueryChainWrapper<ChainlooseJ3LDF0> queryWrapper = chainlooseJ3LDF0Service.query();
        applyQueryConditions(queryWrapper, query);
        return queryWrapper.list();
    }

    /**
     * 机械臂J3传动链松动、负载为7、运动轨迹LDF数据。根据时间范围查询机械臂数据，
     * 或者查询轴的参数（Vcmd: 指令速度、Vfb: 反馈速度、Acmd: 指令加速度、Afb: 反馈加速度、Ecmd: 指令误差、Efb: 反馈电流）。
     */
    @Tool(description = "机械臂J3传动链松动、负载为7、运动轨迹LDF数据。根据时间范围查询机械臂数据，" +
            "或者查询轴的参数（Vcmd: 指令速度、Vfb: 反馈速度、Acmd: 指令加速度、Afb: 反馈加速度、Ecmd: 指令误差、Efb: 反馈电流）。")
    public List<ChainlooseJ3LDF7> queryChainlooseJ3LDF7Data(@ToolParam(description = "机械臂查询的条件") ChainlooseQuery query) {
        log.info("执行机械臂J3负载为7数据查询，参数：{}", query);
        QueryChainWrapper<ChainlooseJ3LDF7> queryWrapper = chainlooseJ3LDF7Service.query();
        applyQueryConditions(queryWrapper, query);
        return queryWrapper.list();
    }

    /**
     * 机械臂J3正常、负载为0、运动轨迹LDF数据。根据时间范围查询机械臂数据，
     * 或者查询轴的参数（Vcmd: 指令速度、Vfb: 反馈速度、Acmd: 指令加速度、Afb: 反馈加速度、Ecmd: 指令误差、Efb: 反馈电流）。
     */
    @Tool(description = "机械臂J3正常、负载为0、运动轨迹LDF数据。根据时间范围查询机械臂数据，" +
            "或者查询轴的参数（Vcmd: 指令速度、Vfb: 反馈速度、Acmd: 指令加速度、Afb: 反馈加速度、Ecmd: 指令误差、Efb: 反馈电流）。")
    public List<NormalLDF0> queryNormalJ3LDF0Data(@ToolParam(description = "机械臂查询的条件") ChainlooseQuery query) {
        log.info("执行机械臂J3正常数据查询，参数：{}", query);
        QueryChainWrapper<NormalLDF0> queryWrapper = normalLDF0Service.query();
        applyQueryConditions(queryWrapper, query);
        return queryWrapper.list();
    }

    /**
     * 机械臂J3负载为0时高电流异常数据。根据时间范围查询机械臂数据，
     * 或者查询轴的参数（Vcmd: 指令速度、Vfb: 反馈速度、Acmd: 指令加速度、Afb: 反馈加速度、Ecmd: 指令误差、Efb: 反馈电流）。
     */
    @Tool(description = "机械臂J3负载为0时高电流异常数据。根据时间范围查询机械臂数据，" +
            "或者查询轴的参数（Vcmd: 指令速度、Vfb: 反馈速度、Acmd: 指令加速度、Afb: 反馈加速度、Ecmd: 指令误差、Efb: 反馈电流）。")
    public List<HighcurrentJ3LDF0> queryHighcurrentJ3LDF0Data(@ToolParam(description = "机械臂查询的条件") ChainlooseQuery query) {
        log.info("执行机械臂J3高电流数据查询，参数：{}", query);
        QueryChainWrapper<HighcurrentJ3LDF0> queryWrapper = highcurrentJ3LDF0Service.query();
        applyQueryConditions(queryWrapper, query);
        return queryWrapper.list();
    }
}